package net.borlis.sample.web.soap.executors.common;

import org.apache.commons.lang.SystemUtils;
import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;

import javax.xml.datatype.XMLGregorianCalendar;
import java.util.Collection;

/**
 * @author alex@borlis.net
 */
public class SoapLogRecursiveStyle extends ToStringStyle {

    private static final ToStringStyle INSTANCE = new SoapLogRecursiveStyle();

    public SoapLogRecursiveStyle() {
        setArrayContentDetail(true);
        setUseShortClassName(true);
        setUseClassName(false);
        setUseIdentityHashCode(false);
        setFieldSeparator(", " + SystemUtils.LINE_SEPARATOR + "  ");
    }

    public static ToStringStyle getInstance() {
        return INSTANCE;
    }

    @Override
    public void appendDetail(StringBuffer buffer, String fieldName, Object value) {
        final String javaPackageName = "java";
        if (!value.getClass().getName().startsWith(javaPackageName)) {
            if (value instanceof XMLGregorianCalendar) {
                buffer.append(SoapUtils.translate((XMLGregorianCalendar) value).toString());
            } else {
                buffer.append(ReflectionToStringBuilder.toString(value, INSTANCE));
            }
        } else {
            super.appendDetail(buffer, fieldName, value);
        }
    }

    @Override
    public void appendDetail(StringBuffer buffer, String fieldName, Collection value) {
        appendDetail(buffer, fieldName, value.toArray());
    }

}
